package com.weapp.common.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;

public class JWTUtil {

  private static final String USER_ID = "userId";

  private static final String SECRET = "c617def701b711eda1d4b02628f9bb3e";

  public static void main(String[] args) {
    String token = JWTUtil.generateJWT("1");
    System.out.println("JWTUtil.validate(token) = " + JWTUtil.validate(token));
    System.out.println("JWTUtil.parseJWT(token) = " + JWTUtil.parseJWT(token));
    System.out.println("JWTUtil.validate(token + 3) = " + JWTUtil.validate(token + 1));
  }

  /**
   * 生成token字符串
   *
   * @param userId
   * @return
   */
  public static String generateJWT(String userId) {
    return JWT.create()
      .withClaim(USER_ID, userId)
      .sign(Algorithm.HMAC256(SECRET));
  }

  /**
   * 从jwt token字符串中解析userId
   *
   * @param jwtToken
   * @return
   */
  public static String parseJWT(String jwtToken) {
    return JWT.decode(jwtToken).getClaim(USER_ID).asString();
  }

  /**
   * 验证token是否非法
   *
   * @param jwtToken
   * @return
   */
  public static Boolean validate(String jwtToken) {
    try {
      Algorithm algorithm = Algorithm.HMAC256(SECRET);
      JWTVerifier verifier = JWT.require(algorithm)
        .build();
      verifier.verify(jwtToken);
    } catch (JWTVerificationException exception) {
      return false;
    }
    return true;
  }
}
